// 淘宝API接口集合
import req from './axios'
import moment from 'moment';
import crypto from 'crypto';
import Config from '../../config/config.config';
const $API = 'http://gw.api.taobao.com/router/rest'
let appsecret = Config.tblmAppSecret
let args = {};

function signFunc(params) {
  args = { // args的时间戳需要实时更新
    app_key: Config.tblmAppKey,
    timestamp: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
    format: 'json',
    v: '2.0',
    sign_method: 'md5'
  }
  for (var key in params) {
    if (typeof params[key] === 'object' && Buffer.isBuffer(params[key])) {
      request.attach(key, params[key], { knownLength: params[key].length, filename: key })
    } else if (typeof params[key] === 'object' && Stream.Readable(params[key]) && !util.is(params[key]).a(String)) {
      request.attach(key, params[key]);
    } else if (typeof params[key] === 'object') {
      args[key] = JSON.stringify(params[key]);
    } else {
      args[key] = params[key];
    }
  }

  let data = { ...params, ...args }
  var sorted = Object.keys(data).sort();
  let basestring = appsecret;
  for (var i = 0, l = sorted.length; i < l; i++) {
    var k = sorted[i];
    basestring += k + data[k];
  }
  basestring += appsecret;
  let sign = hash('md5', basestring).toUpperCase();
  return sign;
}

function hash(method, s, format) {
  var sum = crypto.createHash(method);
  var isBuffer = Buffer.isBuffer(s);
  if (!isBuffer && typeof s === 'object') {
    s = JSON.stringify(sortObject(s));
  }
  sum.update(s, isBuffer ? 'binary' : 'utf8');
  return sum.digest(format || 'hex');
}

// 只通过请求的method方法区分调用，taobao.tbk.dg.vegas.tlj.create
const index = data => req.get(
  `${$API}`, {
    sign: signFunc(data),
    ...args,
    ...data,
  }
);

export default {
  index,
}